package org.contacts.dao.util;

import java.io.*;
import java.sql.*;
import java.util.Properties;

/**
 * Created by nnazarov on 3/28/14.
 */
public class ConnectionFactory {
    private static ConnectionFactory instance = new ConnectionFactory();
    public static String dbUrl;
    public static String dbClass;
    public static String username;
    public static String password;

    private ConnectionFactory() {
        String filepath = "C:\\myworkspace\\project\\github\\contacts\\code\\src\\main\\java\\org\\contacts\\dao\\config\\db.properties";
        try {

            Properties properties = new Properties();
            InputStream inputStream = this.getClass().getResourceAsStream("/db.properties");
            properties.load(inputStream);

            dbUrl = properties.getProperty("db.url");
            dbClass = properties.getProperty("db.class");
            username = properties.getProperty("db.username");
            password = properties.getProperty("db.password");
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    // method to create connection
    private static Connection createConnection() {
        Connection connection = null;

        try {
            Class.forName(dbClass);
            connection = DriverManager.getConnection(dbUrl,
                    username, password);
        }
        catch (SQLException se) {
            se.printStackTrace();
        }
        catch (ClassNotFoundException ce) {
            ce.printStackTrace();
        }

        return connection;
    }

    public static Connection getConnecion() {
        return instance.createConnection();
    }
}
